package com.maxd.controller.mt;

import com.alibaba.fastjson.JSONObject;
import com.maxd.adapter.IgnoreSecurity;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.CommonInfo;
import com.maxd.model.UserInfo;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.utils.Config;
import com.maxd.utils.HttpClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(value = "美团api管理", tags = {"美团api管理"})
@Slf4j
@RequestMapping(value = "/meituan")
public class MtController {

    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private UserRepository userRepository;


    @IgnoreSecurity
    @GetMapping("/generateLink")
    @ApiOperation("美团商品转链")
    public Result generateLink(
            @ApiParam(name = "actId", value = "活动id，可以在联盟活动列表中查看获取")
            String actId,
            @ApiParam(name = "relationId", value = "推广id")
            String relationId,
            @ApiParam(name = "linkType", value = "链接类型，枚举值：1 h5链接 2deeplink(唤起)链接 3中间页唤起链接 4微信小程序唤起路径 5团口令")
            String linkType,
            @ApiParam(name = "shortLink", value = "0表示获取长链1表示获取短链")
            @RequestParam(defaultValue = "0",value ="shortLink" ) String shortLink){
        CommonInfo clientId = commonRepository.findOne(123);
        CommonInfo clientSecret = commonRepository.findOne(124);
        Map<String,String> map=new HashMap<>();
        map.put("appkey",clientId.getValue());//	appkey
        map.put("actId",actId);// 活动id
        map.put("sid",relationId);
        map.put("linkType",linkType);
        String[] array={"appkey","actId","sid","linkType"};
        String sign = genSign(map, array, clientSecret.getValue());
        map.put("sign",sign);//请求签名，计算方法参考文档中签名(sign)生成逻辑
        String data = HttpClientUtil.doGet("https://openapi.meituan.com/api/generateLink", map);
        return ResultUtil.success(JSONObject.parseObject(data));
    }
    @IgnoreSecurity
    @GetMapping("/selectMTCategory")
    @ApiOperation("美团商品类目")
    public Result selectMTCategory(String businessLine,String actId,String pageNo,String pageSize){
        CommonInfo clientId = commonRepository.findOne(123);
        CommonInfo clientSecret = commonRepository.findOne(124);
        Map<String,String> map=new HashMap<>();
        map.put("appkey",clientId.getValue());//	appkey
        map.put("businessLine",businessLine);
        map.put("actId",actId);// 活动id
        map.put("pageNo",pageNo);
        map.put("pageSize",pageSize);
        String[] array={"appkey","businessLine","actId","pageNo","pageSize"};
        String sign = genSign(map, array, clientSecret.getValue());
        map.put("sign",sign);//请求签名，计算方法参考文档中签名(sign)生成逻辑
        String data = HttpClientUtil.doGet("https://openapi.meituan.com/api/mtunion/category", map);
        return ResultUtil.success(JSONObject.parseObject(data));
    }

    @IgnoreSecurity
    @GetMapping("/selectMTCity")
    @ApiOperation("美团城市")
    public Result selectMTCity(String businessLine,String pageNo,String pageSize){
        CommonInfo clientId = commonRepository.findOne(123);
        CommonInfo clientSecret = commonRepository.findOne(124);
        Map<String,String> map=new HashMap<>();
        map.put("appkey",clientId.getValue());//	appkey
        map.put("businessLine",businessLine);
        map.put("pageNo",pageNo);
        map.put("pageSize",pageSize);
        String[] array={"appkey","businessLine","pageNo","pageSize"};
        String sign = genSign(map, array, clientSecret.getValue());
        map.put("sign",sign);//请求签名，计算方法参考文档中签名(sign)生成逻辑
        String data = HttpClientUtil.doGet("https://openapi.meituan.com/api/mtunion/city", map);
        return ResultUtil.success(JSONObject.parseObject(data));
    }

    @IgnoreSecurity
    @GetMapping("/selectMTSku")
    @ApiOperation("美团商品列表")
    public Result selectMTSku(String businessLine,String actId,String categoryId,String cityId,String pageNo,String pageSize){
        CommonInfo clientId = commonRepository.findOne(123);
        CommonInfo clientSecret = commonRepository.findOne(124);
        Map<String,String> map=new HashMap<>();
        map.put("appkey",clientId.getValue());//	appkey
        map.put("businessLine",businessLine);
        map.put("actId",actId);// 活动id
        map.put("categoryId",categoryId);
        map.put("cityId",cityId);
        map.put("pageNo",pageNo);
        map.put("pageSize",pageSize);
        String[] array={"appkey","businessLine","actId","categoryId","cityId","pageNo","pageSize"};
        String sign = genSign(map, array, clientSecret.getValue());
        map.put("sign",sign);//请求签名，计算方法参考文档中签名(sign)生成逻辑
        String data = HttpClientUtil.doGet("https://openapi.meituan.com/api/mtunion/sku", map);
        return ResultUtil.success(JSONObject.parseObject(data));
    }

    @IgnoreSecurity
    @GetMapping("/selectMTGetQualityscorebysid")
    @ApiOperation("优选SID质量分查询")
    public Result selectMTGetQualityscorebysid(String businessLine,String sid,String type,String pageNo,String pageSize,String beginDate,String endDate,String promotionType){
        CommonInfo clientId = commonRepository.findOne(123);
        CommonInfo clientSecret = commonRepository.findOne(124);
        Map<String,String> map=new HashMap<>();
        map.put("appkey",clientId.getValue());//	appkey
        map.put("businessLine",businessLine);//业务线（默认为:4表示优选）
        map.put("ts",System.currentTimeMillis()/1000+"");// 时间戳
        map.put("sid",sid);//推广位sid
        map.put("type",type);//质量分类型（1表示预估类型、2表示实际类型）
        map.put("promotionType",promotionType);//订单质量分类型：CPS类订单=1；CPA类订单=2 默认为CPA类订单
        map.put("beginDate",beginDate);
        map.put("endDate",endDate);
        map.put("pageNo",pageNo);
        map.put("pageSize",pageSize);
        String[] array={"appkey","businessLine","ts","sid","type","promotionType","beginDate","endDate","pageNo","pageSize"};
        String sign = genSign(map, array, clientSecret.getValue());
        map.put("sign",sign);//请求签名，计算方法参考文档中签名(sign)生成逻辑
        String data = HttpClientUtil.doGet("https://openapi.meituan.com/api/getqualityscorebysid", map);
        return ResultUtil.success(JSONObject.parseObject(data));
    }

    @IgnoreSecurity
    @GetMapping("/selectMTPoi")
    @ApiOperation("门店POI查询")
    public Result selectMTPoi(String sid,String pageNo,String pageSize,String longitude,String latitude,String cateId,String secondCateId,String pageTraceId){
        CommonInfo clientId = commonRepository.findOne(123);
        CommonInfo clientSecret = commonRepository.findOne(124);
        Map<String,String> map=new HashMap<>();
        map.put("appkey",clientId.getValue());//	appkey
        map.put("businessLine","2");//固定2=外卖
        map.put("ts",System.currentTimeMillis()/1000+"");// 时间戳
        map.put("sid",sid);//推广位sid
        map.put("longitude",longitude);//举例：120212010，其中120为整数部分，212010为小数部分，详见文档末尾数据示例
        map.put("latitude",latitude);//举例：30208400，其中30为整数部分，208400为小数部分，详见文档末尾数据示例
        map.put("cateId",cateId);//一级品类ID
        map.put("secondCateId",secondCateId);//二级品类ID
        map.put("pageNo",pageNo);
        map.put("pageSize",pageSize);
        map.put("pageTraceId",pageTraceId);
        String[] array={"appkey","businessLine","ts","sid","longitude","latitude","cateId","secondCateId","pageNo","pageSize","pageTraceId"};
        String sign = genSign(map, array, clientSecret.getValue());
        map.put("sign",sign);//请求签名，计算方法参考文档中签名(sign)生成逻辑
        String data = HttpClientUtil.doGet("https://openapi.meituan.com/api/mtunion/poi", map);
        return ResultUtil.success(JSONObject.parseObject(data));
    }



    public static String genSign(Map<String,String> map,String[] array,String SECRET) {
        Arrays.sort(array);
        StringBuilder sb=new StringBuilder(SECRET);
        for(String str:array){
            sb.append(str).append(map.get(str));
        }
        sb.append(SECRET);
        return md5(sb.toString());
    }

    public static String md5(String source) {
        String md5Result = null;
        try {
            byte[] hash = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(source);
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(hash);
            hash = messageDigest.digest();
            md5Result = Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return md5Result;
    }














}
